package com.mitu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        //创建一个ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selector对象
        Selector selector = Selector.open();
        //绑定服务端端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置服务器socket为非阻塞
        serverSocketChannel.configureBlocking(false);
        //将ServerSocketChannel也要注册到Selector上
        //注意关心事件为OP_ACCEPT连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端的连接
        while (true) {
            //服务器等待1s，如果1s后没有事件(连接事件)发生,就返回。
            if (selector.select(1000) == 0) {
                //没有事件发生
                System.out.println("服务器等待了1s,无连接");
                continue;
            }

            //如果返回的不是0(>0),获取到相关的Selector集合tionKey(有事件发生的key)
            //返回>0表示已经获取到关注的事件了
            //selector.selectedKeys()返回的是关注事件的集合
            //通过selectionKeys集合反向获取通道
            final Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //使用迭代器遍历集合
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                //获取到SelectionKey
                SelectionKey key = keyIterator.next();
                //判断该通道发生的是什么事件
                if (key.isAcceptable()) {
                    //连接事件,有新的客户端连接服务器端了
                    //产生SocketChannel分配给新的客户端
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    System.out.println("客户端连接成功,生成了一个SocketChannel" + socketChannel.hashCode());
                    //需要把该SocketChannel也注册到选择器上,关注事件为OP_READ
                    //同时给该socketChannel关联一个ByteBuffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    //通道里发生读的事件
                    //通过key反向获取到对应的Channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该Channel关联的Buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    //读取数据
                    channel.read(buffer);
                    System.out.println("from client data:" + new String(buffer.array()));
                }
                //手动从集合中移除当前的selectionKey,防止重复操作
                keyIterator.remove();
            }
        }
    }
}
